package com.yuanli.cosmeticmirror.persenter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.opengl.EGLContext;
import android.os.Environment;

import androidx.annotation.NonNull;

import com.ljy.cameralibrary.CainCommandEditor;
import com.ljy.cameralibrary.camera.BaseRenderer;
import com.ljy.cameralibrary.camera.CameraController;
import com.ljy.cameralibrary.camera.CameraParam;
import com.ljy.cameralibrary.camera.ICameraController;
import com.ljy.cameralibrary.camera.OnFrameAvailableListener;
import com.ljy.cameralibrary.camera.OnSurfaceTextureListener;
import com.ljy.cameralibrary.listener.OnCaptureListener;
import com.ljy.cameralibrary.recorder.AudioParams;
import com.ljy.cameralibrary.recorder.RecordInfo;
import com.ljy.cameralibrary.recorder.VideoParams;
import com.ljy.cameralibrary.utils.BrightnessUtils;
import com.ljy.cameralibrary.utils.PathConstraints;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yuanli.cosmeticmirror.base.Config;
import com.yuanli.cosmeticmirror.base.Constant;
import com.yuanli.cosmeticmirror.base.WxConstant;
import com.yuanli.cosmeticmirror.utils.BitmapUtils;
import com.yuanli.cosmeticmirror.utils.FileUtils;
import com.yuanli.cosmeticmirror.view.activity.MainActivity;

import java.io.File;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import tv.danmaku.ijk.media.player.MediaInfo;

/**
 * 录制器的presenter
 *
 * @author CainHuang
 * @date 2019/7/7
 */
public class RecordPresenter extends BaseRenderer implements OnSurfaceTextureListener, OnFrameAvailableListener, OnCaptureListener {

    private MainActivity mActivity;

    // 音视频参数
    //    private final VideoParams mVideoParams;
    //    private final AudioParams mAudioParams;
    // 录制操作开始
    private boolean mOperateStarted = false;


    // 最大时长
    private long mMaxDuration;

    // 视频列表
    private List<MediaInfo> mVideoList = new ArrayList<>();

    // 录制音频信息
    private RecordInfo mAudioInfo;
    // 录制视频信息
    private RecordInfo mVideoInfo;

    // 命令行编辑器
    private CainCommandEditor mCommandEditor;

    // 相机控制器
    private final ICameraController mCameraController;

    public RecordPresenter(MainActivity activity) {
        mActivity = activity;
        // 视频录制器
        //        mHWMediaRecorder = new HWMediaRecorder(this);

        // 视频参数
        //        mVideoParams = new VideoParams();
        //        mVideoParams.setVideoPath(getVideoTempPath(mActivity));

        // 音频参数
        //        mAudioParams = new AudioParams();
        //        mAudioParams.setAudioPath(getAudioTempPath(mActivity));

        // 命令行编辑器
        mCommandEditor = new CainCommandEditor();

        // 创建相机控制器
        //        if (CameraApi.hasCamera2(mActivity)) {
        //            mCameraController = new CameraXController(activity, ContextCompat.getMainExecutor(activity));
        //        } else {
        mCameraController = new CameraController(activity);
        //        }
        mCameraController.setOnFrameAvailableListener(this);
        mCameraController.setOnSurfaceTextureListener(this);
        CameraParam.getInstance().brightness = BrightnessUtils.getSystemBrightness(activity);
    }

    /**
     * 启动
     */
    public void onResume() {
        CameraParam.getInstance().captureCallback = this;
        openCamera();
    }

    /**
     * 暂停
     */
    public void onPause() {
        closeCamera();
        CameraParam.getInstance().captureCallback = null;
    }

    /**
     * 切换相机
     */
    public void switchCamera() {
        mCameraController.switchCamera();
    }

    /**
     * 相机缩小放大
     */
    public void cameraZoomOut(int i) {
        mCameraController.handleZoom(i);
    }

    /**
     * 释放资源
     */
    public void release() {
        mActivity = null;
        if (mCommandEditor != null) {
            mCommandEditor.release();
            mCommandEditor = null;
        }
        closeCamera();
    }

    /**
     * 绑定EGLContext
     *
     * @param context
     */
    @Override
    public void onBindSharedContext(EGLContext context) {
        //        mVideoParams.setEglContext(context);
    }

    @Override
    public void onSurfaceTexturePrepared(@NonNull SurfaceTexture surfaceTexture) {
        if (mActivity != null){
            mActivity.bindSurfaceTexture(surfaceTexture);
        }
    }

    @Override
    public void onFrameAvailable(SurfaceTexture surfaceTexture) {
        if (mActivity != null){
            mActivity.onFrameAvailable();
        }
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        mCameraController.openCamera();
        calculateImageSize();
    }

    /**
     * 计算imageView 的宽高
     */
    private void calculateImageSize() {
        int width;
        int height;
        if (mCameraController.getOrientation() == 90 || mCameraController.getOrientation() == 270) {
            width = mCameraController.getPreviewHeight();
            height = mCameraController.getPreviewWidth();
        } else {
            width = mCameraController.getPreviewWidth();
            height = mCameraController.getPreviewHeight();
        }
        //        mVideoParams.setVideoSize(width, height);
        mActivity.updateTextureSize(width, height);
    }

    /**
     * 释放资源
     */
    private void closeCamera() {
        if (mCameraController != null){
            mCameraController.closeCamera();
        }
    }


    /**
     * 获取绑定的Activity
     *
     * @return
     */
    @Override
    public Activity getActivity() {
        return mActivity;
    }

    /**
     * 获取录制视频的段数
     *
     * @return
     */
    public int getRecordVideoSize() {
        return mVideoList.size();
    }

    /**
     * 创建合成的视频文件名
     *
     * @return
     */
    public String generateOutputPath() {
        //        return PathConstraints.getVideoCachePath(mActivity);
        return "";
    }

    /**
     * 获取音频缓存绝对路径
     *
     * @param context
     * @return
     */
    private static String getAudioTempPath(@NonNull Context context) {
        String directoryPath;
        // 判断外部存储是否可用，如果不可用则使用内部存储路径
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            directoryPath = context.getExternalCacheDir().getAbsolutePath();
        } else { // 使用内部存储缓存目录
            directoryPath = context.getCacheDir().getAbsolutePath();
        }
        String path = directoryPath + File.separator + "temp.aac";
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        return path;
    }

    /**
     * 获取视频缓存绝对路径
     *
     * @param context
     * @return
     */
    private static String getVideoTempPath(@NonNull Context context) {
        String directoryPath;
        // 判断外部存储是否可用，如果不可用则使用内部存储路径
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && context.getExternalCacheDir() != null) {
            directoryPath = context.getExternalCacheDir().getAbsolutePath();
        } else { // 使用内部存储缓存目录
            directoryPath = context.getCacheDir().getAbsolutePath();
        }
        String path = directoryPath + File.separator + "temp.mp4";
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        return path;
    }

    /**
     * 截屏回调
     *
     * @param buffer
     * @param width
     * @param height
     */
    @Override
    public void onCapture(final ByteBuffer buffer, final int width, final int height) {
        //        String filePath = PathConstraints.getImageCachePath(mActivity);
        //        BitmapUtils.saveBitmap(FileUtils.getSDCardRoot() + Config.PHOTO_PATH, buffer, width, height);
        Bitmap bitmap = BitmapUtils.getBitmap(buffer, width, height);
        mActivity.saveData(bitmap);
        //        if (mCameraParam.captureListener != null) {
        //            mCameraParam.captureListener.onMediaSelectedListener(filePath, GalleryType.PICTURE);
        //        }
    }

    @Override
    public void onCapture(Bitmap buffer) {
//        Bitmap bitmap = BitmapUtils.getBitmap(buffer, width, height);
        mActivity.saveData(buffer);
    }



    /**
     * 打开微信小程序
     */
    public void openWxApplet(Activity activity) {
        String appId = WxConstant.WX_APP_ID; // 填移动应用(App)的 AppId，非小程序的 AppID
        IWXAPI api = WXAPIFactory.createWXAPI(activity, appId);

        WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
        req.userName = "gh_0ec48e3e2b3f"; // 填小程序原始id
        req.path = "pages/index/index?type=34";
        req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
        api.sendReq(req);
    }
}
